package res

import (
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/push"
	"xr-game-server/dao/resdao"
	"xr-game-server/dto/resdto"
	"xr-game-server/entity"
	"xr-game-server/module/protocol"
)

type ResHandler struct {
}

func initResHandler() {
	protocol.RegItemHandler(protocol.Res, newResHandler())
}

func (this *ResHandler) CanConsume(roleId uint64, item *protocol.ItemModel) bool {
	//TODO implement me
	db := resdao.GetOneRes(roleId, item.Id)
	if db == nil {
		return false
	}
	return db.Val >= item.Val
}

func (this *ResHandler) Consume(roleId uint64, models []*protocol.ItemModel, canPush bool) bool {
	if len(models) == common.Zero {
		return false
	}
	for _, res := range models {
		flag := this.CanConsume(roleId, res)
		if !flag {
			return false
		}
	}
	for _, res := range models {
		db := resdao.GetOneRes(roleId, res.Id)
		res.TypeId = common.Subtract
		if db == nil {
			return false
		}
		res.Old = db.Val
		db.Consume(res.Val)
		res.Current = db.Val
	}
	if canPush {
		caches := resdao.GetResBy(roleId)
		push.Data(roleId, cmd.ResBatch, resdto.NewArrayResDto(caches))
	}
	return true
}

func (this *ResHandler) AddItem(roleId uint64, models []*protocol.ItemModel, canPush bool) {
	if len(models) == common.Zero {
		return
	}
	for _, model := range models {
		model.TypeId = common.Add
		resData := resdao.GetOneRes(roleId, model.Id)
		if resData == nil {
			resData = entity.NewPlayerRes(roleId, model.Id)
			model.Old = resData.Val
			resData.Add(model.Val)
			model.Current = resData.Val
			resdao.AddRes(resData)
		} else {
			model.Old = resData.Val
			resData.Add(model.Val)
			model.Current = resData.Val
		}
	}
	if canPush {
		rets := make([]*entity.PlayerRes, common.Zero)

		for _, model := range models {
			db := resdao.GetOneRes(roleId, model.Id)
			if db != nil {
				rets = append(rets, db)
			}
		}
		if len(rets) > common.Zero {
			push.Data(roleId, cmd.ResBatch, resdto.NewArrayResDto(rets))
		}
	}
}

func newResHandler() protocol.ItemHandler {
	return &ResHandler{}
}
